import vm from '../main.js'
import axios from 'axios'

const qs = require('qs')
let that = vm;
const server = {
  //development: 'https://restapi.FMoneyc.net/',
  //production: 'https://restapi.FMoneyc.net/',
   production: '//api.qtglobal.net',
   development: '//api.qtglobal.net',
   //production: 'http://api.qtglobal.xyz',
  // development: 'http://api.flcrotu.cn',
   //production: 'http://api.flcrotu.cn',
}

const jsonUrl = (json) => {
  let arr = []
  let str = ''
  for (let i in json) {
    str = i + '=' + json[i]
    arr.push(str)
  }
  return arr.join('&')
}

//写一个拦截器

export const fet = (url,data,method,postHeaders) => {
  var user = localStorage.getItem("usertoken");
  axios.defaults.headers.common['language'] = localStorage.getItem("c_i18n")?localStorage.getItem("c_i18n"):'zh_CN';
  if (user) {
      axios.defaults.headers.common['authorization'] = 'Bearer ' + user
  }

  let realUrl = server[process.env.NODE_ENV] + url
  let type = method.toLowerCase()
  let res = {}
  if(type === 'get'){
    res = axios.get(realUrl + '?' + jsonUrl(data))
    .catch(function (error) {
      console.log(error);
      if(error.response.status==401){
          localStorage.removeItem("usertoken");
          localStorage.removeItem("userintro");
          that.$store.commit('resetstate');
          if(data.gologin){
            that.$router.push({
              path: "/login"
            });
          }
      }
    });
  } else if(type === 'post'){
    res = axios.post(realUrl,qs.stringify(data),postHeaders)
    .catch(function (error) {
      console.log(error);
      if(error.response.status==401){
        localStorage.removeItem("usertoken");
        localStorage.removeItem("userintro");
        that.$store.commit('resetstate');
    }
    });
  } else if(type === 'put') {
    res = axios.put(realUrl,qs.stringify(data),postHeaders)
    .catch(function (error) {
      console.log(error);
      if(error.response.status==401){
        localStorage.removeItem("usertoken");
        localStorage.removeItem("userintro");
        that.$store.commit('resetstate');
    }
    });
  } else if(type === 'delete') {
    let strUrl = realUrl;
    if(data){
      if(url=='/user/v1/api/delete'){
        for(var i=0;i<data.length;i++){
          strUrl+="/"+data[i]
        }
      }else{
        for(var i=0;i<data.length;i++){
          if(i==0){
            strUrl+=data[i]
          }else{
            strUrl+=","+data[i]
          }
        }
      }

    }
    res = axios.delete(strUrl,postHeaders)
    .catch(function (error) {
      console.log(error);
      if(error.response.status==401){
        localStorage.removeItem("usertoken");
        localStorage.removeItem("userintro");
        that.$store.commit('resetstate');
    }
    });
  }
  return res
}
